import {createStore} from "stamen";
import {ReducerFn, Reducers} from "stamen/dist/typings";
import Taro from "@tarojs/taro"

export interface UserInfo {
  nickName: string,
  avatarUrl: string,
  gender: string,
  city: string
  country: string
  province: string
  token: string
  openId: string
  mobile: string,
  subjectId: number // 学科id
  subjectName: string  // 学科名称
  isLogin: boolean
}


interface UserReducers<S> extends Reducers<S> {
  set: ReducerFn<S>
  clear: ReducerFn<S>
}

type UserInfoOrNull = UserInfo | null

interface UserStoreState {
  value: UserInfoOrNull
}

// 初始化用户信息
function initUserInfo(): UserInfoOrNull {
  const value = Taro.getStorageSync('userInfo')
  if (!value) return null
  return JSON.parse(value);
}

// @ts-ignore
export default createStore<UserStoreState, UserReducers<UserStoreState>, any>(
  {
    state: {
      value: initUserInfo()
    },
    reducers: {
      set(state, user: UserInfo) {
        state.value = user
        Taro.setStorageSync("userInfo", JSON.stringify(user))
      },
      clear(state) {
        state.value = null
        Taro.removeStorageSync("userInfo")
      },
    }
  }
)
